package com.gxljc.bear.crawler.util;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Json Utils
 * 
 * @author tanghaitao
 * 
 */
public abstract class JsonUtil {

	private static Logger LOG = Logger.getLogger(JsonUtil.class);

	public static ObjectMapper mapper = new ObjectMapper();

	public static Gson gson = new Gson();

	public static String objectToString(Object object) {
		String s = null;
		try {
			s = gson.toJson(object);
		} catch (Exception e) {
			LOG.warn("", e);
			throw new RuntimeException("转换json错误！", e);
		}
		return s;

	}

	@SuppressWarnings("unchecked")
	public static Map<String, Object> stringToMap(String content) {
		try {
			return gson.fromJson(content, LinkedHashMap.class);
			// return mapper.readValue(content, LinkedHashMap.class);
		} catch (Exception e) {
			LOG.warn("", e);
			throw new RuntimeException("转换json错误！", e);
		}

	}

	/**
	 * parse Json to Map
	 * 
	 * @param jsonStr
	 * @return
	 */
	public static Map<String, Object> parseJSON2Map(String jsonStr) {
		Map<String, Object> resultMap = new LinkedHashMap<>();
		if (StringUtils.isBlank(jsonStr) || "null".equals(jsonStr)) {
			return resultMap;
		}
		JSONObject json = JSONObject.fromObject(jsonStr);
		for (Object k : json.keySet()) {
			Object v = json.get(k);
			resultMap.put(k.toString(), v);
		}
		return resultMap;
	}

	/**
	 * parse Json to list
	 * 
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List<Map<String, Object>> parseJSON2List(String jsonStr) {
		if (StringUtils.isBlank(jsonStr)) {
			return null;
		}

		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		try {
			resultList = JSONArray.fromObject(jsonStr);
		} catch (Exception ex) {
			LOG.error(String.format("parseJSON2List error,jsonStr=%s", jsonStr), ex);
		}
		return resultList;
	}

}